<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

use yii\helpers\Json;
use builder\helper\Url;
use builder\helper\App;

/* ====== 分步表单构建器 ====== */

/** @var \yii\web\View $this */
/** @var \builder\form_step\FormStepBuilder $context 当前分步表单组件实例 */
/** @var array $submitConfirm 设置分步表单提交确认框 */
/** @var array $submittedCalls 分步表单提交后的回调，空数组代表不回调 */
/** @var array $fssRedirect 分步表单提交后重定向, 空数组代表无操作 */
/** @var array $extraJs 额外的JS脚本 */
/** @var bool $autoClose 是否提交后自动关闭表单 */
/** @var bool $autoBack 是否提交后自动返回 */

// 上下文对象
$context = $this->context;
?>
<script>
!function (global, top) {"use strict";
    global.ym2App.controller("ym2.ctrl.<?= $context->id ?>", [
        "$scope",
        "$http",
        "ymSpinner",
        "layui",
        "ym2",
        "swal",
        "lodash",
        function ($scope, $http, ymSpinner, layui, ym2, swal, lodash) {
            // 提交URL
            var builderId = "<?= $context->id ?>";
            var topToastr = top.toastr;
            var topLayer = top.layui.layer;
            var topJquery = top.jQuery;
            var topYmSpinner = top.ymSpinner;
            var submitUrl = "<?= $context->submitUrl ?>";
            var submittedCalls = <?= Json::encode($submittedCalls) ?>;
            var submittedRedirectOptions = <?= Json::encode($fssRedirect) ?>;
            var currentMounted = {};

            /**
             * 初始化
             * @private
             */
            $scope._actionInitScope = function () {
                $scope.currentPageIndex = 0;
            };
            $scope._actionInitScope();
            /**
             * 挂载数据
             */
            $scope._actionMountedData = function(callId) {
                if (callId && global.ym2PageDataExport.hasOwnProperty(callId)) {
                    var action = global.ym2PageDataExport[callId];
                    if (ym2.typeOf(action) === 'function') {
                        if (action.call()) {
                            // 挂载
                            currentMounted[callId] = action;
                        } else {
                            return false;
                        }
                    }
                }

                return true;
            };
            /**
             * 下一步
             * @param currentPageIndex
             * @param callId
             */
            $scope.actionNextStep = function (currentPageIndex, callId) {
                if (!$scope._actionMountedData(callId)) { return; }
                $scope.currentPageIndex = currentPageIndex + 1;
            };
            /**
             * 上一步
             * @param currentPageIndex
             */
            $scope.actionPrevStep = function (currentPageIndex) {
                $scope.currentPageIndex = currentPageIndex - 1;
            };
            /**
             * 关闭表单
             */
            $scope.actionClose = function () {
                var layerIndex = topLayer.getFrameIndex(global.name);
                topLayer.close(layerIndex);
                return true;
            };
            /**
             * 返回
             */
            $scope.actionBack = function () {
                global.history.go(-1);
                return true;
            };
            /**
             * 提交事件
             */
            $scope.actionSubmit = function (callId) {
                if (!$scope._actionMountedData(callId)) { return; }
                var isConfirm = <?= (int)$submitConfirm['show'] ?>;
                if (!isConfirm) {
                    $scope._actionRunSubmitRequest();
                } else {
                    ym2.swal.question(
                        top.swal,
                        "<?= $submitConfirm['title'] ?>",
                        "<?= $submitConfirm['content'] ?>",
                        function (result) {
                            //确认提交
                            if (result.isConfirmed) {
                                $scope.$apply(function () {
                                    $scope._actionRunSubmitRequest();
                                });
                            }
                        }
                    );
                }
            };
            /**
             * 获取表单数据
             */
            $scope._actionGetFormData = function () {
                var result = {};
                var pass = true;
                Object.keys(currentMounted).forEach(function (callId) {
                    var action = currentMounted[callId];
                    var tmp = action.call();
                    if (tmp) {
                        result = lodash.merge(result, tmp);
                    } else {
                        pass = false;
                    }
                });

                return pass ? result : false;
            };
            /**
             * 发起提交请求
             * @private
             */
            $scope._actionRunSubmitRequest = function () {
                // 获取表单数据
                var formData = $scope._actionGetFormData();
                if (formData === false) { return; }

                // 发起请求
                var flag = ymSpinner.show();
                $http.post(submitUrl, formData).then(function (result) {
                    ymSpinner.hide(flag);
                    var data = result.data;
                    switch (data.code) {
                        case <?= App::params('http.res.success') ?>: //业务成功
                            // 成功轻提示
                            topToastr.success(data.msg);

                            // 执行Successful回调
                            $scope._actionSubmittedCallback( "successCallback" );

                            // 表单提交后重定向,空数组代表无操作
                            $scope._actionSubmittedRedirect(data.data || []);
<?php if ($autoClose): ?>
                            // 自动关闭弹窗
                            var layerIndex = topLayer.getFrameIndex(global.name);
                            topLayer.close(layerIndex);
<?php elseif ($autoBack): ?>
                            // 自动返回上一页
                            global.history.go(-1);
<?php endif; ?>

                            break;
                        case <?= App::params('http.res.failure') ?>: //业务失败
                            topToastr.error(data.msg);
                            // 执行Failure回调
                            $scope._actionSubmittedCallback( "failureCallback" );
                            break;
                        case <?= App::params('http.res.unauthorized') ?>://授权失效, 去登录
                            // 授权失效, 去登录
                            ym2.swal.timer(
                                top.swal,
                                data.msg,
                                "自动跳转; <a href='<?= Url::to(App::params('admin.route.login'), '') ?>' target='_top'>立即跳转<a/>",
                                function () {
                                    top.open("<?= Url::to(App::params('admin.route.login'), '') ?>", "_self");
                                },
                                3000
                            );

                            break;
                        default://其他
                            topToastr.error(data.msg);
                    }

                }, function (error) {
                    ymSpinner.hide(flag);
                    topToastr.error(error.data || "系统错误, 发起请求失败!");
                    global.console.error(error);
                });
            };
            /**
             * 表单提交后重定向,空数组代表无操作
             * @param data
             * @private
             */
            $scope._actionSubmittedRedirect = function (data) {
                var L = Object.keys(submittedRedirectOptions).length;
                if (L <= 0) {
                    return;
                }

                var type = submittedRedirectOptions.type;
                var url = submittedRedirectOptions.route;
                var params = submittedRedirectOptions.params || [];

                if (ym2.keys(params).length) {
                    params = ym2.fillParams(params, data);
                    url = ym2.addUrlQueryParam(url, params);
                }

                switch (type) {
                    case "modal"://modal
                        // layer动态唯一索引
                        var activeIndex = topLayer.index;
                        // modal title
                        var title = submittedRedirectOptions.title || '';
                        // modal width
                        var width = submittedRedirectOptions.width || "100%";
                        // modal height
                        var height = submittedRedirectOptions.height || "100%";
                        // modal footer close btn
                        var footerCloseBtn = submittedRedirectOptions.closeBtn;
                        // layer screen obj
                        var layerScreenObj = ym2.layerScreenOptions(width);
                        var refererName = ym2.layerRefererWindowName( submittedRedirectOptions.refererWindow );

                        // var loadingFlag = topYmSpinner.show("加载中...");
                        // iframe 模态框
                        var layerCf = {
                            type: 2, // iframe
                            //skin: 'layui-layer-win10',
                            area: [layerScreenObj.width, height],
                            title: title,
                            shade: 0.3, // 遮罩透明度
                            shadeClose: false, // 点击遮罩区域，关闭弹层
                            closeBtn: submittedRedirectOptions.titleCloseBtn,
                            maxmin: submittedRedirectOptions.titleMaxminBtn, // 允许全屏最小化
                            anim: 0, // 0-6 的动画形式，-1 不开启
                            scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                            content: url,
                            success: function(layero, index, that){
                                // topYmSpinner.hide( loadingFlag );
                                // 弹层的最外层元素的 jQuery 对象
                                //console.log(layero);
                                // 弹层的索引值
                                //console.log(index);
                                // 弹层内部原型链中的 this --- 2.8+
                                //console.log(that);
                                // 获取iframe的窗口对象, 添加来源追踪
                                var iframeWin = top[layero.find("iframe")[0]["name"]];
                                iframeWin.__REFERER_WIN_NAME = refererName;
                                //键盘事件关闭
                                topJquery(".ym2_kc_" + activeIndex).focus().on("keydown", function (e) {
                                    // 空格和回车键
                                    if (e.keyCode === 13 || e.keyCode === 32) {
                                        topJquery(this).trigger("click");
                                    }
                                });
                            },
                        };
                        if (footerCloseBtn) {
                            layerCf.btn = ['<span class="ym2_keydown_close ym2_kc_' + activeIndex + '" tabindex="0">关闭</span>'];
                        }

                        topLayer.open(layerCf);
                        break;
                    case "page"://page
                        var target = submittedRedirectOptions.target;
                        var owin;
                        eval("owin = " + submittedRedirectOptions.window);
                        owin.open(url, target);

                        break;
                }
            };
            /**
             * 提交后回调
             * @param {String} callbackName "successCallback"、"failureCallback"
             * @private
             */
            $scope._actionSubmittedCallback = function ( callbackName ) {
                callbackName = callbackName || "successCallback";
                var callbacks = submittedCalls[ callbackName ] || [],
                    callbackWindows = Object.keys( callbacks );
                if ( callbackWindows.length <= 0 ) {
                    return;
                }

                callbackWindows.forEach(function (key) {
                    var callbackMethod = callbacks[ key ];

                    if ( key === "self" ) { //self
                        var selfCbkExport = global.ym2CbkExport || {};
                        if (!callbackMethod.length) {
                            // 回调所有
                            Object.keys(selfCbkExport).forEach(function (key) {
                                /* $scope 当前表单域 */
                                selfCbkExport[key].call();
                            });
                        } else {
                            // 指定回调
                            Object.keys(selfCbkExport).forEach(function (key) {
                                if (lodash.indexOf(callbackMethod, key) !== -1) {
                                    /* $scope 当前表单域 */
                                    selfCbkExport[key].call();
                                }
                            });
                        }
                    } else if ( key.substring(0, 6) === "parent" && global !== global.parent ) { //parent.parent.*
                        var keysMap = key.split('.');
                        var currentWin = global;
                        var refererWinName = currentWin.__REFERER_WIN_NAME;

                        var parentWin;
                        for (var i = 0; i < keysMap.length; i++) {
                            parentWin = refererWinName ? top[ refererWinName ] : currentWin.parent;
                            currentWin = parentWin;
                            refererWinName = parentWin.__REFERER_WIN_NAME;
                        }

                        var parentCbkExport = parentWin.ym2CbkExport || {};
                        if ( !callbackMethod.length ) {
                            // 回调所有
                            Object.keys(parentCbkExport).forEach(function (key) {
                                /* $scope 当前表单域 */
                                parentCbkExport[key].call();
                            });
                        } else {
                            // 指定回调
                            Object.keys(parentCbkExport).forEach(function (key) {
                                if (lodash.indexOf(callbackMethod, key) !== -1) {
                                    /* $scope 当前表单域 */
                                    parentCbkExport[key].call();
                                }
                            });
                        }
                    } else {
                        console.warn(key + " No callback. ");
                    }

                });
            };
            //额外的JS脚本
            <?= !empty($extraJs) ? implode("\n", $extraJs) : '' ?>

        }]);
}(window, top);
</script>
